import React, { useState, useEffect } from 'react';
import { useParams, useNavigate, Link } from 'react-router-dom';
import { workAPI, userAPI } from '../services/api';
import './styles.css';

function AuthorPage() {
  const [authorInfo, setAuthorInfo] = useState(null);
  const [authorWorks, setAuthorWorks] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [isLoggedIn, setIsLoggedIn] = useState(false);
  const [isCurrentUser, setIsCurrentUser] = useState(false);
  const [currentUserData, setCurrentUserData] = useState(null);
  const [isDeleting, setIsDeleting] = useState(false);
  
  const { userId } = useParams();
  const navigate = useNavigate();
  
  // 检查登录状态并加载作者信息和作品
  useEffect(() => {
    checkLoginStatus();
    if (userId) {
      fetchAuthorInfo();
      fetchAuthorWorks();
    }
  }, [userId]);
  
  // 检查用户登录状态并验证是否是当前用户
  const checkLoginStatus = () => {
    const isLoggedInStorage = localStorage.getItem('isLoggedIn') === 'true';
    setIsLoggedIn(isLoggedInStorage);
    
    if (isLoggedInStorage) {
      try {
        const storedUserData = localStorage.getItem('userData');
        if (storedUserData) {
          const userData = JSON.parse(storedUserData);
          
          setCurrentUserData(userData);
          
          // 检查当前登录用户是否为作者本人
          if (userData&& userData.userId === userId) {
            setIsCurrentUser(true);
            console.log('当前用户正在查看自己的主页');
          } else {
            setIsCurrentUser(false);
          }
        }
      } catch (error) {
        console.error('解析用户数据失败', error);
      }
    }
  };
  
  // 获取作者信息
  const fetchAuthorInfo = async () => {
    try {
      setLoading(true);
      const userWorkInfoId = {
        userId: String(userId),
      };
      console.log('获取作者信息，参数:', userWorkInfoId);
      const response = await userAPI.getUserInfo(userWorkInfoId);
      
      if (response) {
        if(response.result==null){
            setError('作者信息不存在');
        }
        setAuthorInfo(response.result);
        console.log('作者信息:', response);
      } else {
        navigate('/login');
      }
    } catch (err) {
      console.error('获取作者信息失败:', err);
      setError('获取作者信息时发生错误');
    }
  };
  
  // 获取作者的作品
  const fetchAuthorWorks = async () => {
    try {
    const userWorkInfoId = {
        userId: String(userId),
        workId: "1"
      };
      const response = await workAPI.getUserWorks(userWorkInfoId);
      if (response && response.result) {
        setAuthorWorks(Array.isArray(response.result) ? response.result : []);
        
      } else {
        setAuthorWorks([]);
      }
    } catch (err) {
      console.error('获取作者作品失败:', err);
      setError('获取作者作品时发生错误');
    } finally {
      setLoading(false);
    }
  };
  
  // 返回首页
  const goToHome = () => {
    navigate('/');
  };
  
  // 处理删除文章
  const handleDeleteWork = async (workId, event) => {
    event.stopPropagation(); // 阻止事件冒泡，防止触发文章点击
    
    if (!window.confirm('确定要删除这篇文章吗？此操作无法撤销。')) {
      return;
    }
    
    try {
      setIsDeleting(true);
      const workIdObj = { userId: currentUserData.userId, workId: workId };
      const response = await workAPI.deleteWork(workIdObj);
      
      if (response && (response.code === 200 || response.status === 'success')) {
        // 删除成功，从列表中移除该文章
        setAuthorWorks(prevWorks => prevWorks.filter(work => work.workId !== workId));
        alert('文章已成功删除');
        window.location.reload();
      } else {
        alert(response?.message || '删除失败，请稍后重试');
      }
    } catch (err) {
      console.error('删除文章失败:', err);
      alert('删除文章时发生错误，请稍后重试');
    } finally {
      setIsDeleting(false);
    }
  };
  
  // 格式化日期显示
  const formatDate = (dateString) => {
    if (!dateString) return '未知日期';
    
    const date = new Date(dateString);
    return date.toLocaleString('zh-CN', { 
      year: 'numeric', 
      month: '2-digit', 
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    });
  };

  return (
    <div className="author-page-container">
      <header className="author-page-header">
        <button className="back-button" onClick={goToHome}>返回首页</button>
        <h1 className="clickable" onClick={goToHome}>Board Demo</h1>
        <div></div> {/* 占位以保持标题居中 */}
      </header>

      <div className="author-page-content">
        {loading ? (
          <div className="loading">加载中...</div>
        ) : error ? (
          <div className="error-message">{error}</div>
        ) : (
          <>
            <div className="author-profile">
              <div className="author-header">
                <div className="author-avatar">
                  {authorInfo?.avatar ? (
                    <img src={authorInfo.avatar} alt={`${authorInfo.nickName || '未知用户'}的头像`} />
                  ) : (
                    <div className="default-avatar">{(authorInfo?.nickName || '未知')[0]}</div>
                  )}
                </div>
                
                <div className="author-info">
                  <h1>{authorInfo?.nickName || '未知用户'}</h1>
                  <p className="author-description">{authorInfo?.description || '这个用户很懒，还没有填写简介'}</p>
                  <div className="author-stats">
                    <div className="stat-item">
                      <span className="stat-label">作品数 </span>
                      <span className="stat-value">{authorInfo?.articleCount}</span>
                     
                    </div>
                  </div>
                </div>
              </div>
            </div>
            
            <div className="author-works">
              <h2>作品列表</h2>
              
              {authorWorks.length === 0 ? (
                <div className="no-articles">暂无作品</div>
              ) : (
                <div className="articles-list">
                  {authorWorks.map(work => (
                    <div className="article-card" key={work.workId}>
                      <div className="article-header">
                        <h3 
                          className="article-title clickable" 
                          onClick={() => navigate(`/article/${work.workId}`)}
                        >
                          {work.title}
                        </h3>
                        {/* 仅在当前用户查看自己的作者页面时显示删除按钮 */}
                        {isCurrentUser && (
                          <button 
                            className="delete-button"
                            onClick={(e) => handleDeleteWork(work.workId, e)}
                            disabled={isDeleting}
                            title="删除文章"
                          >
                            ✕
                          </button>
                        )}
                      </div>
                      <p className="article-description">{work.description || '暂无简介'}</p>
                      <div className="article-meta">
                        <span className="article-time">发布时间：{formatDate(work.createdAt)}</span>
            
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </div>
          </>
        )}
      </div>
    </div>
  );
}

export default AuthorPage;
